﻿using LearningEnglish.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LearningEnglish.Controllers
{
    public static class ControllerExtension
    {
        /// <summary>
        /// 当状态为正常以外的情况时，则抛出异常
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="status"></param>
        public static void HandleStatus(this Controller controller,MyX.DSL.XSimpleStatus status)        
        {
            if (status.Status != MyX.DSL.XSimpleStatus.MessageStatus.Ok)
                throw new Exception(status.Result);
        }

        /// <summary>
        /// 获取本次请求中的操作用户        
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static Guid GetRequestUser(this Controller controller)
        {
            try
            {
                var ticket = controller.Request.Headers["ticket"];
                if (string.IsNullOrWhiteSpace(ticket))
                    throw new Exception("该次请求无票据消息");
                var tokenRD = (from p in VM.Tokens where p.Has(Guid.Parse(ticket)) select p).Single();
                if (tokenRD.IsTimeOut(Guid.Parse(ticket)))
                    throw new Exception("访问票据超时");
                return tokenRD.EntityID;
            }
            catch (Exception e)
            {
                throw new Exception("获取请求者身份失败 ：" + e.Message);
            }            
        }
    }
}